﻿/*
 * $Revision: 1.2 $ $Date: 2009/05/28 12:30:06 $
 */
package net.wangit.app.user;

import net.wangit.LabelUtil;
import net.wangit.UserSupport;
import net.wangit.app.AppResource;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionResult;
import net.wangit.framework.util.RequestUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Type;
import net.wangit.support.action.TransactionAction;
import net.wangit.util.Checker;
import net.wangit.util.DateUtil;
import net.wangit.util.ValidateCode;

public class LoginAction extends TransactionAction {
	private static final String LOG_LAST = "update AUSER set lasttime=logintime,lastip=loginip where userid=?";
	private static final String LOG_CURR = "update AUSER set logintime=?,loginip=? where userid=?";
	private static final int[] TYPES_CURR = new int[] { Type.TIMESTAMP,
			Type.VARCHAR, Type.VARCHAR };

	public void doAction(DB db, ActionContext ac) throws Exception {
		String userId = ac.getRequestParameter("login.userid");
		String password = ac.getRequestParameter("login.password");
		if (!UserSupport.login(ac, userId, password)) {
			// 用户名或密码错
			ac.getActionResult().setSuccessful(false);
		} else if (!validateCode(ac)) {
			// 验证码错误
			ActionResult ar = ac.getActionResult();
			ar.setSuccessful(false);
			ar.addError(LabelUtil.get(ac, AppResource.FILE,
					AppResource.LOGIN_CODE_ERROR));
		} else {
			// SS0
		}
		// 语言设置
		String lang = ac.getRequestParameter("login.lang");
		if (!Checker.isEmpty(lang)) {
			ac.getVisitor().setLocaleString(lang);
		}
		// 更新登录日志
		db.execute(LOG_LAST, userId, Type.VARCHAR);
		String loginTime = DateUtil.getCurrentDatetime();
		String loginIp = RequestUtil.getIp();
		String[] values = new String[] { loginTime, loginIp, userId };
		db.execute(LOG_CURR, values, TYPES_CURR);
		// 记录打开窗口方式
		String clean = ac.getRequestParameter("login.clean");
		ac.setSessionAttribute("app.login.clean", "1".equals(clean) ? "1"
						: "0");
	}

	private boolean validateCode(ActionContext ac) {
		String code = ac.getRequestParameter("login.code");
		if (code == null) {
			return true;// 未设验证码时不验证
		} else {
			return ValidateCode.validate(ac, code);
		}
	}

}
